﻿using System;
using System.Collections.Generic;
using System.IO;

namespace HostTool.Core
{
    /// <summary>
    /// 文件操作
    /// </summary>
    public class FileOperate
    {
        public FileInfo Prototype { get; private set; }

        private static Dictionary<int, string> _errorMessage;

        public FileOperate(string path)
        {
            Prototype = new FileInfo(path);
        }

        public FileOperate(FileInfo prototype)
        {
            Prototype = prototype;

            Initialization();
        }

        /// <summary>
        /// 类型初始化
        /// </summary>
        private void Initialization()
        {
            if (!Prototype.Exists) throw new Exception(Prototype.FullName + _errorMessage[0]);

            _errorMessage = new Dictionary<int, string>
                {
                    {1, "文件不存在"}
                };
        }

        /// <summary>
        /// 读取文件所有内容，返回字符串类型
        /// </summary>
        /// <returns></returns>
        public string Read()
        {
            using (StreamReader streamReader = new StreamReader(Prototype.FullName))
            {
                return streamReader.ReadToEnd();
            }
        }

        /// <summary>
        /// 创建新文件，写入内容
        /// </summary>
        /// <param name="content"></param>
        public void CreateText(string content)
        {
            using (StreamWriter streamWriter = Prototype.CreateText())
            {
                streamWriter.Write(content);
                streamWriter.Flush();
                streamWriter.Close();
            }
        }
    }
}
